package com.moduls.interfaceFunction.core;

import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 */
@Configuration
public class AuthorConfigurationFilter {
    @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }

    @Bean
    public FilterRegistrationBean testFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new TokenAuthorFilter());//添加过滤器
        registration.addUrlPatterns("/api/*");//设置过滤路径，/*所有路径
        registration.addInitParameter("name", "alue");//添加默认参数
        registration.setName("TokenAuthorFilter");//设置优先级
        registration.setOrder(1);//设置优先级
        return registration;
    }

    public class TokenAuthorFilter implements Filter {
        @Override
        public void destroy() {
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain
                filterChain)
                throws IOException, ServletException {
            HttpServletRequest httprequest = (HttpServletRequest) request;
            HttpServletResponse httpresponse = (HttpServletResponse) response;

           /* String token = httprequest.getParameter("token");

            if (token == null || token.isEmpty()) {
                httpresponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "用户授权认证没有通过,客户端请求参数中无token信息");
                return;
            } else {
                AuthorService authorService = AuthorFactory.createProduct(AuthorType.Cache);
                boolean b = authorService.validate(token);
                if (b == false) {
                    httpresponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "用户授权认证没有通过,用户验证失败!");
                    return;
                }
            }*/

            filterChain.doFilter(request, response);
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
        }
    }
}